'use client'

import { useState, useEffect } from 'react'
import { useParameterPermissions } from '@/hooks/use-parameter-permissions'
import { useAuth } from '@/hooks/use-auth'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'

export default function DebugSpecialtyFlowPage() {
  const [selectedSpecialty, setSelectedSpecialty] = useState('procurement')
  const [debugLog, setDebugLog] = useState<string[]>([])
  
  const { user } = useAuth()
  const {
    fields,
    loading,
    error,
    getFieldsByDataSource,
    getUserDataSources
  } = useParameterPermissions('table_c2', 1)

  // 添加调试日志
  const addLog = (message: string) => {
    const timestamp = new Date().toLocaleTimeString()
    setDebugLog(prev => [...prev, `[${timestamp}] ${message}`])
  }

  // 专业到数据来源的映射
  const getSpecialtyDataSources = (specialty: string): string[] => {
    const mapping: Record<string, string[]> = {
      'procurement': ['P'],
      'design': ['E'],
      'monitoring': ['M'],
      'construction': ['C'],
      'operations': ['O', 'R'],
      'all': ['C', 'E', 'P', 'R']  // 硬编码所有数据来源
    }
    return mapping[specialty] || []
  }

  const getSpecialtyName = (specialty: string) => {
    const names: Record<string, string> = {
      'procurement': '采购',
      'design': '设计',
      'monitoring': '监测',
      'construction': '施工',
      'operations': '运维',
      'all': '全部'
    }
    return names[specialty] || specialty
  }

  const getDataSourceColor = (source: string) => {
    const colors: Record<string, string> = {
      'P': 'bg-blue-100 text-blue-800',
      'E': 'bg-green-100 text-green-800',
      'M': 'bg-orange-100 text-orange-800',
      'O': 'bg-purple-100 text-purple-800',
      'C': 'bg-yellow-100 text-yellow-800',
      'R': 'bg-red-100 text-red-800'
    }
    return colors[source] || 'bg-gray-100 text-gray-800'
  }

  // 专业切换处理
  const handleSpecialtyChange = (newSpecialty: string) => {
    addLog(`=== 专业切换开始 ===`)
    addLog(`从 "${getSpecialtyName(selectedSpecialty)}" 切换到 "${getSpecialtyName(newSpecialty)}"`)
    
    setSelectedSpecialty(newSpecialty)
    
    // 获取新专业对应的数据来源
    const newDataSources = getSpecialtyDataSources(newSpecialty)
    addLog(`新专业对应的数据来源: [${newDataSources.join(', ')}]`)
    
    // 分析每个数据来源的字段
    newDataSources.forEach(source => {
      const sourceFields = getFieldsByDataSource(source)
      addLog(`数据来源 ${source}: 找到 ${sourceFields.length} 个字段`)
      
      if (sourceFields.length > 0) {
        sourceFields.forEach(field => {
          addLog(`  - ${field.field_name} (${field.data_source}) [可见:${field.isVisible}, 可编辑:${field.canEdit}]`)
        })
      } else {
        addLog(`  - 数据来源 ${source} 没有找到任何字段`)
      }
    })
    
    addLog(`=== 专业切换完成 ===`)
  }

  // 初始化时的调试信息
  useEffect(() => {
    if (!loading && fields.length > 0) {
      addLog(`=== 初始化调试信息 ===`)
      addLog(`用户: ${user?.full_name} (${user?.role_name})`)
      addLog(`总字段数: ${fields.length}`)
      
      // 按数据来源分组统计
      const fieldsBySource = fields.reduce((acc, field) => {
        if (!acc[field.data_source]) acc[field.data_source] = []
        acc[field.data_source].push(field)
        return acc
      }, {} as Record<string, any[]>)
      
      Object.entries(fieldsBySource).forEach(([source, sourceFields]) => {
        addLog(`数据来源 ${source}: ${sourceFields.length} 个字段`)
      })
      
      addLog(`用户有权限的数据来源: [${getUserDataSources().join(', ')}]`)
      addLog(`=== 初始化完成 ===`)
    }
  }, [loading, fields, user])

  if (loading) {
    return <div className="p-8">加载中...</div>
  }

  if (error) {
    return <div className="p-8 text-red-600">错误: {error}</div>
  }

  // 获取当前专业的数据来源和字段
  const currentDataSources = getSpecialtyDataSources(selectedSpecialty)
  const currentFields = currentDataSources.flatMap(source => getFieldsByDataSource(source))

  return (
    <div className="p-8 space-y-6">
      <h1 className="text-2xl font-bold">专业切换数据流调试</h1>
      
      {/* 专业选择控制 */}
      <Card>
        <CardHeader>
          <CardTitle>专业选择</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center space-x-4 mb-4">
            <label className="text-sm font-medium text-gray-600">专业:</label>
            <select
              value={selectedSpecialty}
              onChange={(e) => handleSpecialtyChange(e.target.value)}
              className="px-3 py-2 border rounded-md text-sm bg-white min-w-[120px]"
            >
              <option value="procurement">采购</option>
              <option value="design">设计</option>
              <option value="monitoring">监测</option>
              <option value="construction">施工</option>
              <option value="operations">运维</option>
              <option value="all">全部</option>
            </select>
            
            <Button onClick={() => setDebugLog([])}>清空日志</Button>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <div className="text-sm font-medium text-gray-600">当前专业</div>
              <div className="text-lg font-semibold">{getSpecialtyName(selectedSpecialty)}</div>
            </div>
            <div>
              <div className="text-sm font-medium text-gray-600">数据来源</div>
              <div className="flex flex-wrap gap-1">
                {currentDataSources.map(source => (
                  <Badge key={source} className={getDataSourceColor(source)}>
                    {source}
                  </Badge>
                ))}
              </div>
            </div>
            <div>
              <div className="text-sm font-medium text-gray-600">字段数量</div>
              <div className="text-lg font-semibold">{currentFields.length}</div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 当前字段详情 */}
      <Card>
        <CardHeader>
          <CardTitle>当前专业字段详情</CardTitle>
        </CardHeader>
        <CardContent>
          {currentDataSources.map(source => {
            const sourceFields = getFieldsByDataSource(source)
            return (
              <div key={source} className="mb-4">
                <h4 className="font-medium mb-2 flex items-center space-x-2">
                  <Badge className={getDataSourceColor(source)}>{source}</Badge>
                  <span>数据来源 ({sourceFields.length} 个字段)</span>
                </h4>
                
                {sourceFields.length > 0 ? (
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-2 ml-4">
                    {sourceFields.map(field => (
                      <div key={field.id} className="text-sm border rounded p-2">
                        <div className="font-medium">{field.field_name}</div>
                        <div className="text-gray-600 text-xs">
                          ID: {field.id} | 可见: {field.isVisible ? '是' : '否'} | 可编辑: {field.canEdit ? '是' : '否'}
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-gray-500 ml-4">没有找到字段</div>
                )}
              </div>
            )
          })}
        </CardContent>
      </Card>

      {/* 调试日志 */}
      <Card>
        <CardHeader>
          <CardTitle>调试日志</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="bg-gray-100 p-4 rounded max-h-96 overflow-y-auto">
            <pre className="text-xs whitespace-pre-wrap">
              {debugLog.length > 0 ? debugLog.join('\n') : '暂无日志'}
            </pre>
          </div>
        </CardContent>
      </Card>

      {/* 原始数据检查 */}
      <Card>
        <CardHeader>
          <CardTitle>原始数据检查</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div>
              <h4 className="font-medium mb-2">所有字段按数据来源分组</h4>
              {['C', 'E', 'P', 'R'].map(source => {
                const sourceFields = fields.filter(f => f.data_source === source)
                return (
                  <div key={source} className="mb-2">
                    <Badge className={getDataSourceColor(source)}>{source}</Badge>
                    <span className="ml-2">{sourceFields.length} 个字段</span>
                    {sourceFields.length > 0 && (
                      <div className="text-xs text-gray-600 ml-6">
                        {sourceFields.map(f => f.field_name).join(', ')}
                      </div>
                    )}
                  </div>
                )
              })}
            </div>
            
            <div>
              <h4 className="font-medium mb-2">getFieldsByDataSource 函数测试</h4>
              {['C', 'E', 'P', 'R'].map(source => {
                const result = getFieldsByDataSource(source)
                return (
                  <div key={source} className="text-sm">
                    <code>getFieldsByDataSource('{source}') = {result.length} 个字段</code>
                  </div>
                )
              })}
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
